﻿using System;
using System.Windows;
using Microsoft.VisualBasic;
using System.Windows.Forms;

namespace ContentManager
{
    public partial class MainForm
    {

        private SAPModule SAPModule = new SAPModule();
        private System.Array SAPRepositorys;

        private System.Array SAPCategories;

        private string OText;
        private string[] OTextArray;
        private int AnzahlZeilen;
        private int AnzahlFiles;
        private int FileNumber;
        private string FormText;         

        public MainForm()
        {
            InitializeComponent();
            FormText = ContentManager.Properties.Resources.FormName + Application.ProductVersion;            
            this.ID_FileName.Text = (String)ContentManager.Properties.Settings.Default["IDFileName"];
            this.Content_FileName.Text = (String)ContentManager.Properties.Settings.Default["ContentFileName"];
            this.maxLines.Text = (String)ContentManager.Properties.Settings.Default["maxPHIOS"];
        }

        private void Form1_Load(System.Object sender, System.EventArgs e)
        {
            this.Text = FormText;
#if DEBUG 
            this.Button_Read_ID_Liste.Enabled = true;
            this.Button_Split_ID_Liste.Enabled = true;
            this.Button_Export.Enabled = true;
            this.Button_Import.Enabled = true;
            this.Button_Check.Enabled = true;
            this.Button_Back.Enabled = true;
            this.Button_Forward.Enabled = true;
            this.Button_ReadLocal_ID_Liste.Enabled = true;
#endif
        }

        private void LogonSAP_Click(System.Object sender, System.EventArgs e)
        {
            SAPModule.R3Logon();
            if (SAPModule.isconnected == true)
            {
                SAPCategories = SAPModule.ReadTable_first_Column("SDOKSTCAE");
                Kategorie.DataSource = SAPCategories;
                SAPRepositorys = SAPModule.ReadTable_first_Column("CREP_HTTP");
                Repository.DataSource = SAPRepositorys;
                Button_Read_ID_Liste.Enabled = true;
                Button_ReadLocal_ID_Liste.Enabled = true;
                Button_Check.Enabled = true;
                Kategorie.Text = ContentManager.Properties.Resources.SelectNow;
                Repository.Text = ContentManager.Properties.Resources.SelectNow;
                this.Text = this.Text + " - " + SAPModule.R3Connection.SystemID;

            }
        }

        private void Read_ID_Liste_Click(System.Object sender, System.EventArgs e)
        {
            if (Repository.Text == "" | Repository.Text == ContentManager.Properties.Resources.SelectNow | Kategorie.Text == "" | Kategorie.Text == ContentManager.Properties.Resources.SelectNow)
            {
                Interaction.MsgBox(ContentManager.Properties.Resources.SelectRepository, MsgBoxStyle.Critical);
                return;
            }

            if (SAPModule.isconnected == false)
            {
                Interaction.MsgBox(ContentManager.Properties.Resources.NoConnection, MsgBoxStyle.Critical);
                return;
            }

            SAPModule.Call_RSCMSLST(this.Kategorie.Text, this.Repository.Text, this.ID_FileName.Text);
            Refresh_OTextArray(ID_FileName.Text);
            Button_Split_ID_Liste.Enabled = true;
            Button_Read_ID_Liste.Enabled = false;
            Button_ReadLocal_ID_Liste.Enabled = false;
            SAPModule.R3Connection.Reconnect();
        }


        public void Refresh_OTextArray(string filename, string impText = "")
        {
            System.Text.Encoding enc = System.Text.Encoding.GetEncoding(1252);
            int n = 0;

            if (!string.IsNullOrEmpty(filename))
            {
                try
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(filename, enc);
                    OText = sr.ReadToEnd();
                    sr.Close();
                    string[] ITextArray = OText.Split(Strings.ChrW(13));
                    OTextArray = new string[ITextArray.Length];

                    foreach (string Zeile in ITextArray)
                    {
                        if (n > 0) OTextArray[n] = Strings.Mid(Zeile, 2);                       
                        OTextArray[n] = Zeile;
                        n++;
                    }

                }
                catch
                {
                }

            }
            else
            {
                OText = impText;
                string[] ITextArray = OText.Split(Strings.ChrW(10));
                OTextArray = new string[ITextArray.Length];

                foreach (string Zeile in ITextArray)
                {
                    OTextArray[n] = Zeile;
                    n++;
                }
            }

            RichTextBox1.Text = OText;
            this.maxLines_TextChanged(null, null);
            this.numberFiles_TextChanged(null, null);

        }



        private void Split_ID_Liste_Click(System.Object sender, System.EventArgs e)
        {
            string FileName = ID_FileName.Text;
            string SaveFileName = null;

            System.IO.StreamWriter sw = null;
            System.Text.Encoding enc = System.Text.Encoding.GetEncoding(1252);
            //System.Text.Encoding enc = System.Text.Encoding.UTF8;

            int n = 0;
            int p = 0;
            int k = 0;

            if (FileName == null)
                return;

            FileNumber = 1;
            Button_Export.Text = ContentManager.Properties.Resources.Export + FileNumber;
            Button_Import.Text = ContentManager.Properties.Resources.Import + FileNumber;
            Button_Export.Enabled = true;
            Button_Import.Enabled = true;
            maxLines.Enabled = false;
            numberFiles.Enabled = false;
            Button_Read_ID_Liste.Enabled = false;
            Button_ReadLocal_ID_Liste.Enabled = false;
            Button_Split_ID_Liste.Enabled = false;
            Kategorie.Enabled = false;
            Repository.Enabled = false;
            ID_FileName.Enabled = false;
            Content_FileName.Enabled = false;
            Button_Forward.Enabled = true;

            for (p = 1; p <= AnzahlFiles; p++)
            {
                SaveFileName = System.IO.Path.GetDirectoryName(FileName) + "\\" + System.IO.Path.GetFileNameWithoutExtension(FileName) + p + System.IO.Path.GetExtension(FileName);
                sw = new System.IO.StreamWriter(SaveFileName, false, enc);
                string[] STextArray = new string[AnzahlZeilen];
                for (n = 0; n <= AnzahlZeilen - 1; n++)
                {
                    try
                    {
                        k = n + (p - 1) * AnzahlZeilen; 
                        STextArray[n] = OTextArray[k];
                        if (k == (p - 1) * AnzahlZeilen)
                        {
                            if (p != 1)
                            {
                                STextArray[n] = STextArray[n].Remove(0, 1);                               
                            }
                            sw.Write(STextArray[n]);
                        }

                        else if (k == (p * AnzahlZeilen) - 1)
                        {
                            sw.Write("\r" + STextArray[n] + "\n");
                        }

                        else if (k < OTextArray.Length)
                        {
                            //sw.WriteLine(STextArray[n]);
                            sw.Write("\r" + STextArray[n]);

                        }                        
                    }
                    catch
                    {
                        sw.Close();
                        return;
                    }
                }
                sw.Close();
            }

        }

        private void maxLines_TextChanged(System.Object sender, System.EventArgs e)
        {
            if (!Information.IsNumeric(maxLines.Text))
            {
                maxLines.Text = "";
            }
            else
            {
                try
                {
                    if (!string.IsNullOrEmpty(maxLines.Text))
                    {
                        AnzahlZeilen = System.Convert.ToInt32(maxLines.Text); // maxLines.Text;
                    }
                    else
                    {
                        AnzahlZeilen = OTextArray.Length;
                    }
                    
                    AnzahlFiles = (int)System.Math.Ceiling(((double)OTextArray.Length) / ((double)AnzahlZeilen));
                    numberFiles.Text = AnzahlFiles.ToString();
                    Lines_ID_List.Text = OTextArray.Length.ToString();
                }
                catch
                {
                }
            }
        }

        private void ID_FileName_DoubleClick(System.Object sender, System.EventArgs e)
        {
            try
            {
                SaveFileDialog1.InitialDirectory = System.IO.Path.GetDirectoryName(ID_FileName.Text);
                SaveFileDialog1.FileName = System.IO.Path.GetFileName(ID_FileName.Text);

            }
            catch (Exception ex)
            {
            }

            if (SaveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ID_FileName.Text = SaveFileDialog1.FileName;
            }
        }

        private void Content_FileName_DoubleClick(System.Object sender, System.EventArgs e)
        {
            try
            {
                SaveFileDialog1.InitialDirectory = System.IO.Path.GetDirectoryName(Content_FileName.Text);
                SaveFileDialog1.FileName = System.IO.Path.GetFileName(Content_FileName.Text);

            }
            catch (Exception ex)
            {
            }

            if (SaveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Content_FileName.Text = SaveFileDialog1.FileName;
            }
        }


        private void Kategorie_SelectedIndexChanged(System.Object sender, System.EventArgs e)
        {

        }

        private void Repository_SelectedIndexChanged(System.Object sender, System.EventArgs e)
        {

        }

        private void Button_Export_Click(System.Object sender, System.EventArgs e)
        {

            if (SAPModule.isconnected == false)
            {
                Interaction.MsgBox(ContentManager.Properties.Resources.NoConnection, MsgBoxStyle.Critical);
#if DEBUG
#else
                return;
#endif
            }


            if (AnzahlFiles == 0)
            {
                Interaction.MsgBox(ContentManager.Properties.Resources.NumberFilesZero, MsgBoxStyle.Critical);
#if DEBUG
#else
                return;
#endif

            }

            if (FileNumber == 1)
            {
                if (Interaction.MsgBox(ContentManager.Properties.Resources.IsChecked, MsgBoxStyle.YesNo) == MsgBoxResult.No)
                {
                    return;
                }
            }

            Button_Import.Text = ContentManager.Properties.Resources.Import;
            Button_Import.Enabled = false;
            Button_Back.Enabled = true;
            Button_Forward.Enabled = true;

            string FileName = null;
            string IDFileName = null;

            FileName = System.IO.Path.GetDirectoryName(Content_FileName.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(Content_FileName.Text) + FileNumber + System.IO.Path.GetExtension(Content_FileName.Text);
            IDFileName = System.IO.Path.GetDirectoryName(ID_FileName.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(ID_FileName.Text) + FileNumber + System.IO.Path.GetExtension(ID_FileName.Text);
            SAPModule.Call_RSCMSEXL(this.Kategorie.Text, this.Repository.Text, IDFileName, FileName);
            ProgressBar_Export.Value = (100 / AnzahlFiles) * FileNumber;
            SAPModule.R3Connection.Reconnect();
            FileNumber++;
            if (FileNumber > AnzahlFiles)
            {
                FileNumber = 1;
                Button_Export.Enabled = false;
                Button_Export.Text = ContentManager.Properties.Resources.Export;
                // Interaction.MsgBox("Ändern Sie nun die contenserver.ini und Restarten den IIS", MsgBoxStyle.OkOnly);
                // Interaction.MsgBox("Überprüfen in SAP, ob die Umschaltung erfolgreich war (Dokument kann nicht mehr anzeigt werden)", MsgBoxStyle.OkOnly);
                Button_Import.Enabled = true;
                Button_Import.Text = ContentManager.Properties.Resources.Import + FileNumber;
            }
            else
            {
                Button_Export.Text = ContentManager.Properties.Resources.Export + FileNumber;
            }
            this.Refresh();
        }

        private void Button_Logoff_SAP_Click(System.Object sender, System.EventArgs e)
        {
            if (SAPModule.isconnected == true)
            {
                SAPModule.R3Connection.Logoff();
            }

            Button_Read_ID_Liste.Enabled = false;
            Button_ReadLocal_ID_Liste.Enabled = true;
            Button_Split_ID_Liste.Enabled = false;
            Button_Export.Enabled = false;
            Button_Import.Enabled = false;
            maxLines.Enabled = true;
            numberFiles.Enabled = true;
            Kategorie.DataSource = null;
            Repository.DataSource = null;
            Kategorie.Enabled = true;
            Repository.Enabled = true;            
            ID_FileName.Enabled = true;
            Content_FileName.Enabled = true;
            ProgressBar_Export.Value = 0;
            ProgressBar_Import.Value = 0;
            maxLines.Text = (String)ContentManager.Properties.Settings.Default["maxPHIOS"]; 
            RichTextBox1.Text = null;
            this.Text = FormText;
            Button_Back.Enabled = false;
            Button_Forward.Enabled = false;
            Button_Check.Enabled = false;
        }

        private void numberFiles_TextChanged(System.Object sender, System.EventArgs e)
        {
            if (!Information.IsNumeric(numberFiles.Text))
            {
                numberFiles.Text = "";
            }
            else
            {
                try
                {
                    if (!string.IsNullOrEmpty(numberFiles.Text))
                    {
                        AnzahlFiles = System.Convert.ToInt32(numberFiles.Text);
                    }
                    else
                    {
                        AnzahlFiles = 1;
                    }
                    AnzahlZeilen = (int)System.Math.Ceiling(((double)OTextArray.Length) / ((double)AnzahlFiles));
                    maxLines.Text = AnzahlZeilen.ToString();
                    Lines_ID_List.Text = OTextArray.Length.ToString();
                }
                catch
                {
                }
            }
        }

        private void Button_Import_Click(System.Object sender, System.EventArgs e)
        {
            if (SAPModule.isconnected == false)
            {
                Interaction.MsgBox(ContentManager.Properties.Resources.NoConnection, MsgBoxStyle.Critical);
                return;
            }

            if (AnzahlFiles == 0)
            {
                Interaction.MsgBox(ContentManager.Properties.Resources.NumberFilesZero, MsgBoxStyle.Critical);
                return;
            }

            if (FileNumber == 1)
            {
                if (Interaction.MsgBox(ContentManager.Properties.Resources.SelectedRightOne, MsgBoxStyle.YesNo) == MsgBoxResult.No)
                {
                    return;
                }
            }

            Button_Export.Text = ContentManager.Properties.Resources.Export;
            Button_Export.Enabled = false;
            Button_Back.Enabled = true;
            Button_Forward.Enabled = true;

            string FileName = null;
            FileName = System.IO.Path.GetDirectoryName(Content_FileName.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(Content_FileName.Text) + FileNumber + System.IO.Path.GetExtension(Content_FileName.Text);

            SAPModule.Call_RSCMSIM(this.Repository.Text, FileName);

            ProgressBar_Import.Value = (100 / AnzahlFiles) * FileNumber;
            SAPModule.R3Connection.Reconnect();
            FileNumber = FileNumber + 1;
            if (FileNumber > AnzahlFiles)
            {
                FileNumber = 1;
                Button_Import.Enabled = false;
                Button_Import.Text = ContentManager.Properties.Resources.Import;
                // Interaction.MsgBox("Fertig !!!" + Strings.Chr(13) + "Überprüfen Sie nun die Konsistenz mit Report DMS_KPRO_CHECK1" + Strings.Chr(13) + "Löschen sie die ggf. die lokal erzeugten Dateien.", MsgBoxStyle.OkOnly);
            }
            else
            {
                Button_Import.Text = ContentManager.Properties.Resources.Import + FileNumber;
            }
            this.Refresh();
        }

        private void Button_Back_Click(System.Object sender, System.EventArgs e)
        {
            if (FileNumber > 1)
            {
                FileNumber = FileNumber - 1;
            }
            else
            {
                Button_Back.Enabled = false;
                Button_Import.Enabled = true;
                Button_Export.Enabled = true;
                Button_Forward.Enabled = true;
            }
            if (Button_Export.Enabled == true)
            {
                Button_Export.Text = ContentManager.Properties.Resources.Export + FileNumber;
                ProgressBar_Export.Value = (100 / AnzahlFiles) * (FileNumber - 1);
            }
            if (Button_Import.Enabled == true)
            {
                Button_Import.Text = ContentManager.Properties.Resources.Import + FileNumber;
                ProgressBar_Import.Value = (100 / AnzahlFiles) * (FileNumber - 1);
            }
        }

        private void Button_Forward_Click(System.Object sender, System.EventArgs e)
        {
            if (FileNumber < AnzahlFiles)
            {
                FileNumber = FileNumber + 1;
                Button_Back.Enabled = true;
            }
            else
            {
                Button_Forward.Enabled = false;
                Button_Import.Enabled = true;
                Button_Export.Enabled = true;
                Button_Back.Enabled = true;
            }
            if (Button_Export.Enabled == true)
            {
                Button_Export.Text = ContentManager.Properties.Resources.Export + FileNumber;
                ProgressBar_Export.Value = (100 / AnzahlFiles) * (FileNumber - 1);
            }
            if (Button_Import.Enabled == true)
            {
                Button_Import.Text = ContentManager.Properties.Resources.Import + FileNumber;
                ProgressBar_Import.Value = (100 / AnzahlFiles) * (FileNumber - 1);
            }
        }

        private void Button_Split_ID_Liste_MouseHover(object sender, System.EventArgs e)
        {
            string Hinweis = null;
            Hinweis = ContentManager.Properties.Resources.ImportNote;
            ToolTip1.Show(Hinweis, this, 10, 80, 10000);
        }


        private void Button_Check_Click(System.Object sender, System.EventArgs e)
        {
            if (SAPModule.isconnected == false)
            {
                Interaction.MsgBox(ContentManager.Properties.Resources.NoConnection, MsgBoxStyle.Critical);
#if DEBUG
#else
                return;
#endif
            }
            
            string P_CDB = "";
            string P_CCS = "X";
            MsgBoxResult Switch = default(MsgBoxResult);
            Switch = Interaction.MsgBox(ContentManager.Properties.Resources.KproOrContent, MsgBoxStyle.YesNo);
            if (Switch == MsgBoxResult.No)
            {
                P_CDB = "X";
                P_CCS = "";
            }
            SAPModule.Call_DMS_KPRO_CHECK1(this.Repository.Text, P_CDB, P_CCS);
            SAPModule.R3Connection.Reconnect();
        }



        private void RichTextBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                  System.Windows.Forms.Form Dialog = new PhioDeleteInListForm();

                  System.Windows.Forms.TextBox Textbox = ((PhioDeleteInListForm)Dialog).TextBox1;
                  string leftText = null;
                  string rightText = null;
                  int Laenge = 0;

                  ((PhioDeleteInListForm)Dialog).TextBox1.Text = RichTextBox1.SelectedText;
                  Dialog.ShowDialog();

                  RichTextBox1.Find(Textbox.Text, System.Windows.Forms.RichTextBoxFinds.WholeWord);


                  if (Dialog.DialogResult == System.Windows.Forms.DialogResult.OK)
                  {
                      if (RichTextBox1.SelectionLength == 0)
                      {
                          Interaction.MsgBox(ContentManager.Properties.Resources.PhiosNotFound, MsgBoxStyle.Information);
                          return;
                      }

                      Laenge = RichTextBox1.SelectionStart - 1;
                      if (Laenge < 0)
                      {
                          Laenge = 0;
                          leftText = Strings.Left(RichTextBox1.Text, Laenge);
                          Laenge = RichTextBox1.TextLength - RichTextBox1.SelectionStart - RichTextBox1.SelectionLength - 1;
                      }
                      else
                      {
                          leftText = Strings.Left(RichTextBox1.Text, Laenge);
                          Laenge = RichTextBox1.TextLength - RichTextBox1.SelectionStart - RichTextBox1.SelectionLength;
                      }
                      if (Laenge < 0)
                          Laenge = 0;
                      rightText = Strings.Right(RichTextBox1.Text, Laenge);
                      RichTextBox1.Text = leftText + rightText;
                      this.Refresh_OTextArray("", RichTextBox1.Text);
                  }
              }

        }

        private void ReadLocal_Click(object sender, EventArgs e)
        {
            
            Refresh_OTextArray(ID_FileName.Text);
            Button_Split_ID_Liste.Enabled = true;
        }       

        
        
    }
}
